<?php

namespace backend\controllers;

use Yii;
use backend\models\Major;
use backend\models\MajorSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\UploadForm;
use yii\web\UploadedFile;
use yii\helpers\ArrayHelper;
use yii\web\Response;
use backend\models\Department;
use backend\models\KMajorCatalog;
use backend\models\School;

/**
 * MajorController implements the CRUD actions for Major model.
 */
class MajorController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Major models.
     * @return mixed
     */
    public function actionIndex()
    {
        //TODO  查询范围限制：当前学校只能查当前学校   市县级只能查下级学校
        $searchModel = new MajorSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    /**
     * 待审核专业的列表
     * @return string
     */
    public function actionAuditList()
    {
        $searchModel = new MajorSearch();
        $dataProvider = $searchModel->search(array_merge_recursive(
            Yii::$app->request->queryParams,
            ['MajorSearch' => ['ZT'=>0]]
        ));

        return $this->render('auditlist', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    
    /**
     * 审核专业.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionAudit($id)
    {
        $model = $this->findModel($id);
        
        if(Yii::$app->request->isPost && $model->load(Yii::$app->request->post())){
            
            //TODO 国控专业（医学、教育、司法）需区级终审。这里要判断当前管理员权限
            //TODO 如果是驳回，发送消息给学校
            
            $model->save() ;
            return $this->redirect(['view', 'id' => $model->ID]);
        } 
        
        $ztDisplayName = "";
        if($model->ZT == 0){$ztDisplayName = "待审核";}
        else if($model->ZT == -1){$ztDisplayName = "驳回";}
        else if($model->ZT == 1){$ztDisplayName = "已批准";}
    
        return $this->render('audit', [
            'model' => $this->findModel($id),
            'ztDisplayName'=>$ztDisplayName,
        ]);
    }
    
    
    /**
     * Displays a single Major model.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $ztDisplayName = "";
        if($model->ZT == 0){$ztDisplayName = "待审核";}
        else if($model->ZT == -1){$ztDisplayName = "驳回";}
        else if($model->ZT == 1){$ztDisplayName = "已批准";}

        return $this->render('view', [
            'model' => $this->findModel($id),
            'ztDisplayName'=>$ztDisplayName,
        ]);
    }

    /**
     * Creates a new Major model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Major();       
        if(Yii::$app->request->isPost && $model->load(Yii::$app->request->post())){
            $model->PYFA = UploadedFile::getInstance($model, 'PYFA');            
            //存储路径: upload/PYFA/学校ID/目录下
            $saveDir = 'upload/PYFA/'.$model->XXID;
            $savePath = $saveDir.'/'.md5(time().rand(0,9)).".".$model->PYFA->getExtension();
            if (!file_exists($saveDir)) {mkdir($saveDir , 0777, true);}
            
            if($model->PYFA->saveAs($savePath)) {
                $model->PYFA = $savePath;
            }
            
            //状态设置为待审核，预防前端注入
            $model->ZT = 0;
            
            //TODO 一：规则配置
            //TODO 1 XXID 需在school表
            //TODO 2 BMID 需在department表中，并且学校与XXID对应
            //TODO 3 专业代码、专业名称、版本目录必须是在kmajorcatalog表中存在
            
            //TODO 二：发送审核消息给上级
            
            //TODO 三：校级用户只能添加当前学校。
            
            $model->save();
            return $this->redirect(['view', 'id' => $model->ID]);
        }        

        //学校列表array(XXID=>ZWMC) 
		//TODO 应该根据当前用户限制可以选择的学校
        $schoolList = School::find()->select(['ZWMC'])->indexBy('ID')->column();

        return $this->render('create', [
            'model' => $model,
            'schoolList'=>$schoolList, 
        ]);
    }

    /**
     * Updates an existing Major model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        //TODO 在待审核状态下不能做任何修改，防止在审核期间做了内容修改。
        
        $model = $this->findModel($id);
        
        if(Yii::$app->request->isPost && $model->load(Yii::$app->request->post())){
            //上传新的培养方案
            if($model->PYFA = UploadedFile::getInstance($model, 'PYFA')){
                //存储路径: upload/PYFA/学校ID/目录下
                $saveDir = 'upload/PYFA/'.$model->XXID;
                $savePath = $saveDir.'/'.md5(time().rand(0,9)).".".$model->PYFA->getExtension();
                if (!file_exists($saveDir)) {mkdir($saveDir , 0777, true);}
                
                if($model->PYFA->saveAs($savePath)) {
                    $model->PYFA = $savePath;
                }
            }else{
                unset($model->PYFA);
            }            
            
            //TODO 是否在已批准状态不能修改学校XXID？？
            //TODO 是否在已批准状态专业代码、专业名称、专业版本是否能修改？？
            
            if($model->oldAttributes['ZT'] == -1 || $model->oldAttributes['ZT'] == 0 ){
                $model->ZT = 0; //被驳回的，保存后状态变为待审核
                $model->BHYY = ""; //清空驳回原因
                
                //TODO 发送消息给上级
                
            }else{
                unset($model->ZT);//其他状态不能修改
            }
            
            $model->save();
            return $this->redirect(['view', 'id' => $model->ID]);        
        }
        
        
        //学校列表array(XXID=>ZWMC)
        $schoolList = School::find()->select(['ZWMC'])->indexBy('ID')->column();
        //部门院系列表
        $deparmentList = Department::find()
                        ->select(['BMMC'])
                        ->andWhere(['XXID'=>$model->XXID])
                        ->indexBy('ID')->column();   
        //专业目录选择列表
        $kMajorCatalog = KMajorCatalog::find()->select(['ZYMC','MLBB'])->andWhere(['ZYDM'=>$model->ZYDM])->asArray()->all();
        
        return $this->render('update', [
            'model' => $model,
            'schoolList'=>$schoolList,
            'deparmentList'=>$deparmentList,
            'kMajorCatalog'=>$kMajorCatalog
        ]);
    }
    
    /**
     * 列出学校下面的所有部门
     * @param int $xxid 学校id
     */
    public function actionListSchoolDepartment($xxid){
        $deparmentList = Department::getDepartID($xxid);
        Yii::$app->response->format=Response::FORMAT_JSON;
        return $deparmentList;
    }
    
    /**
     * 列出学校下面的所有部门
     * @param int|string $zydm 专业代码
     * @param string $zymc 专业名称
     */
    public function actionGetKMajorCatalog($zydm){
        $kMajorCatalog = KMajorCatalog::find()->select(['ZYMC','MLBB'])->andWhere(['ZYDM'=>$zydm])->asArray()->all();       
        Yii::$app->response->format=Response::FORMAT_JSON;
        return $kMajorCatalog;
    }
    

    /**
     * Deletes an existing Major model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Major model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Major the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Major::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
    
    
    
}
